<template>
  <div class="friend-request-list">
    <!-- 头部 -->
    <div class="request-header">
      <h3>好友请求</h3>
      <el-badge :value="pendingRequestCount" :hidden="pendingRequestCount === 0">
        <el-button 
          type="text" 
          @click="refreshRequests"
          :loading="isLoading"
          icon="el-icon-refresh"
        >
          刷新
        </el-button>
      </el-badge>
    </div>

    <!-- 标签页 -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick">
      <el-tab-pane label="收到的请求" name="received">
        <div class="request-count">
          共 {{ receivedRequests.length }} 条请求，{{ pendingReceivedRequests.length }} 条待处理
        </div>
        
        <!-- 批量操作 -->
        <div v-if="selectedRequests.length > 0" class="batch-actions">
          <el-button 
            type="primary" 
            size="small"
            @click="batchAccept"
            :loading="isBatchProcessing"
          >
            批量接受 ({{ selectedRequests.length }})
          </el-button>
          <el-button 
            type="danger" 
            size="small"
            @click="batchReject"
            :loading="isBatchProcessing"
          >
            批量拒绝 ({{ selectedRequests.length }})
          </el-button>
        </div>

        <!-- 请求列表 -->
        <div class="request-list">
          <div 
            v-for="request in receivedRequests" 
            :key="request.id"
            class="request-item"
            :class="{ 'request-item--pending': request.status === 'PENDING' }"
          >
            <el-checkbox 
              v-if="request.status === 'PENDING'"
              v-model="selectedRequests"
              :label="request.id"
              class="request-checkbox"
            />
            
            <div class="request-avatar">
              <el-avatar :size="40" :src="request.fromUser?.avatar">
                {{ request.fromUser?.nickname?.charAt(0) }}
              </el-avatar>
            </div>
            
            <div class="request-content">
              <div class="request-info">
                <span class="request-name">{{ request.fromUser?.nickname || '未知用户' }}</span>
                <span class="request-time">{{ formatTime(request.createdAt) }}</span>
              </div>
              
              <div v-if="request.message" class="request-message">
                {{ request.message }}
              </div>
              
              <div class="request-status">
                <el-tag 
                  :type="getStatusType(request.status)"
                  size="small"
                >
                  {{ getStatusText(request.status) }}
                </el-tag>
                
                <span v-if="request.processedAt" class="processed-time">
                  {{ formatTime(request.processedAt) }}
                </span>
              </div>
            </div>
            
            <div v-if="request.status === 'PENDING'" class="request-actions">
              <el-button 
                type="primary" 
                size="small"
                @click="acceptRequest(request)"
                :loading="processingRequests.has(request.id)"
              >
                接受
              </el-button>
              <el-button 
                type="danger" 
                size="small"
                @click="showRejectDialog(request)"
                :loading="processingRequests.has(request.id)"
              >
                拒绝
              </el-button>
            </div>
          </div>
          
          <div v-if="receivedRequests.length === 0" class="empty-state">
            <el-empty description="暂无好友请求" />
          </div>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="发送的请求" name="sent">
        <div class="request-count">
          共 {{ sentRequests.length }} 条请求，{{ pendingSentRequests.length }} 条待处理
        </div>
        
        <!-- 请求列表 -->
        <div class="request-list">
          <div 
            v-for="request in sentRequests" 
            :key="request.id"
            class="request-item"
          >
            <div class="request-avatar">
              <el-avatar :size="40" :src="request.toUser?.avatar">
                {{ request.toUser?.nickname?.charAt(0) }}
              </el-avatar>
            </div>
            
            <div class="request-content">
              <div class="request-info">
                <span class="request-name">{{ request.toUser?.nickname || '未知用户' }}</span>
                <span class="request-time">{{ formatTime(request.createdAt) }}</span>
              </div>
              
              <div v-if="request.message" class="request-message">
                {{ request.message }}
              </div>
              
              <div class="request-status">
                <el-tag 
                  :type="getStatusType(request.status)"
                  size="small"
                >
                  {{ getStatusText(request.status) }}
                </el-tag>
                
                <span v-if="request.rejectReason" class="reject-reason">
                  拒绝原因：{{ request.rejectReason }}
                </span>
              </div>
            </div>
            
            <div v-if="request.status === 'PENDING'" class="request-actions">
              <el-button 
                type="warning" 
                size="small"
                @click="cancelRequest(request)"
                :loading="processingRequests.has(request.id)"
              >
                取消
              </el-button>
            </div>
          </div>
          
          <div v-if="sentRequests.length === 0" class="empty-state">
            <el-empty description="暂无发送的请求" />
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 拒绝对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝好友请求"
      width="400px"
    >
      <el-form>
        <el-form-item label="拒绝原因">
          <el-input
            v-model="rejectReason"
            type="textarea"
            :rows="3"
            placeholder="请输入拒绝原因（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="rejectDialogVisible = false">取消</el-button>
        <el-button 
          type="danger" 
          @click="confirmReject"
          :loading="processingRequests.has(currentRejectRequest?.id)"
        >
          确认拒绝
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useFriendRequestsStore, useAuthStore } from '@/stores'
import type { FriendRequest } from '@/types'
import { format } from 'date-fns'

// Store
const friendRequestsStore = useFriendRequestsStore()
const authStore = useAuthStore()

// 响应式数据
const activeTab = ref('received')
const selectedRequests = ref<number[]>([])
const processingRequests = ref(new Set<number>())
const isBatchProcessing = ref(false)
const rejectDialogVisible = ref(false)
const rejectReason = ref('')
const currentRejectRequest = ref<FriendRequest | null>(null)

// 计算属性
const receivedRequests = computed(() => friendRequestsStore.receivedRequests)
const sentRequests = computed(() => friendRequestsStore.sentRequests)
const pendingReceivedRequests = computed(() => friendRequestsStore.pendingReceivedRequests)
const pendingSentRequests = computed(() => friendRequestsStore.pendingSentRequests)
const pendingRequestCount = computed(() => friendRequestsStore.pendingRequestCount)
const isLoading = computed(() => friendRequestsStore.isLoading)

// 方法
const formatTime = (date: Date) => {
  return format(new Date(date), 'MM-dd HH:mm')
}

const getStatusType = (status: string) => {
  switch (status) {
    case 'PENDING': return 'warning'
    case 'ACCEPTED': return 'success'
    case 'REJECTED': return 'danger'
    case 'CANCELLED': return 'info'
    case 'EXPIRED': return 'info'
    default: return 'info'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'PENDING': return '待处理'
    case 'ACCEPTED': return '已接受'
    case 'REJECTED': return '已拒绝'
    case 'CANCELLED': return '已取消'
    case 'EXPIRED': return '已过期'
    default: return '未知'
  }
}

const handleTabClick = () => {
  selectedRequests.value = []
}

const refreshRequests = async () => {
  if (!authStore.user?.id) return
  
  try {
    await friendRequestsStore.loadAllRequests(authStore.user.id, true)
    ElMessage.success('刷新成功')
  } catch (error) {
    ElMessage.error('刷新失败')
  }
}

const acceptRequest = async (request: FriendRequest) => {
  if (!authStore.user?.id) return
  
  processingRequests.value.add(request.id)
  
  try {
    await friendRequestsStore.acceptFriendRequest(request.id, authStore.user.id)
    ElMessage.success('已接受好友请求')
  } catch (error) {
    ElMessage.error('接受请求失败')
  } finally {
    processingRequests.value.delete(request.id)
  }
}

const showRejectDialog = (request: FriendRequest) => {
  currentRejectRequest.value = request
  rejectReason.value = ''
  rejectDialogVisible.value = true
}

const confirmReject = async () => {
  if (!currentRejectRequest.value || !authStore.user?.id) return
  
  processingRequests.value.add(currentRejectRequest.value.id)
  
  try {
    await friendRequestsStore.rejectFriendRequest(
      currentRejectRequest.value.id, 
      authStore.user.id, 
      rejectReason.value
    )
    ElMessage.success('已拒绝好友请求')
    rejectDialogVisible.value = false
  } catch (error) {
    ElMessage.error('拒绝请求失败')
  } finally {
    processingRequests.value.delete(currentRejectRequest.value.id)
  }
}

const cancelRequest = async (request: FriendRequest) => {
  if (!authStore.user?.id) return
  
  try {
    await ElMessageBox.confirm('确定要取消这个好友请求吗？', '确认取消', {
      type: 'warning'
    })
    
    processingRequests.value.add(request.id)
    
    await friendRequestsStore.cancelFriendRequest(request.id, authStore.user.id)
    ElMessage.success('已取消好友请求')
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('取消请求失败')
    }
  } finally {
    processingRequests.value.delete(request.id)
  }
}

const batchAccept = async () => {
  if (!authStore.user?.id || selectedRequests.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要接受选中的 ${selectedRequests.value.length} 个好友请求吗？`, 
      '批量接受', 
      { type: 'info' }
    )
    
    isBatchProcessing.value = true
    
    const requests = selectedRequests.value.map(id => ({
      requestId: id,
      action: 'accept' as const
    }))
    
    const result = await friendRequestsStore.batchProcessRequests(requests, authStore.user.id)
    
    ElMessage.success(`成功处理 ${result.success} 个请求，失败 ${result.failed} 个`)
    selectedRequests.value = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量处理失败')
    }
  } finally {
    isBatchProcessing.value = false
  }
}

const batchReject = async () => {
  if (!authStore.user?.id || selectedRequests.value.length === 0) return
  
  try {
    await ElMessageBox.confirm(
      `确定要拒绝选中的 ${selectedRequests.value.length} 个好友请求吗？`, 
      '批量拒绝', 
      { type: 'warning' }
    )
    
    isBatchProcessing.value = true
    
    const requests = selectedRequests.value.map(id => ({
      requestId: id,
      action: 'reject' as const,
      reason: '批量拒绝'
    }))
    
    const result = await friendRequestsStore.batchProcessRequests(requests, authStore.user.id)
    
    ElMessage.success(`成功处理 ${result.success} 个请求，失败 ${result.failed} 个`)
    selectedRequests.value = []
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量处理失败')
    }
  } finally {
    isBatchProcessing.value = false
  }
}

// 生命周期
onMounted(async () => {
  if (authStore.user?.id) {
    await friendRequestsStore.loadAllRequests(authStore.user.id)
  }
})
</script>

<style scoped>
.friend-request-list {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.request-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border-bottom: 1px solid #ebeef5;
}

.request-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
}

.request-count {
  padding: 8px 16px;
  font-size: 12px;
  color: #909399;
  background-color: #f5f7fa;
}

.batch-actions {
  padding: 8px 16px;
  background-color: #ecf5ff;
  border-bottom: 1px solid #d9ecff;
}

.request-list {
  flex: 1;
  overflow-y: auto;
}

.request-item {
  display: flex;
  align-items: flex-start;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
  transition: background-color 0.2s;
}

.request-item:hover {
  background-color: #f5f7fa;
}

.request-item--pending {
  background-color: #fdf6ec;
}

.request-checkbox {
  margin-right: 12px;
  margin-top: 8px;
}

.request-avatar {
  margin-right: 12px;
}

.request-content {
  flex: 1;
  min-width: 0;
}

.request-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.request-name {
  font-weight: 500;
  color: #303133;
}

.request-time {
  font-size: 12px;
  color: #909399;
}

.request-message {
  font-size: 14px;
  color: #606266;
  margin-bottom: 8px;
  word-break: break-word;
}

.request-status {
  display: flex;
  align-items: center;
  gap: 8px;
}

.processed-time,
.reject-reason {
  font-size: 12px;
  color: #909399;
}

.request-actions {
  display: flex;
  gap: 8px;
  margin-left: 12px;
}

.empty-state {
  padding: 40px;
  text-align: center;
}

@media (max-width: 768px) {
  .request-item {
    padding: 8px 12px;
  }
  
  .request-actions {
    flex-direction: column;
    gap: 4px;
  }
  
  .request-actions .el-button {
    font-size: 12px;
    padding: 4px 8px;
  }
}
</style>